package com.ls.herostory.channel.handler;

import com.google.protobuf.GeneratedMessageV3;
import com.ls.herostory.msg.GameMsgProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liangsu
 * @version v1.0
 * @Description
 * @Date 2020/10/12 10:15
 * @since
 */
public class GameMsgEncoder extends ChannelOutboundHandlerAdapter {

    private final static Logger logger = LoggerFactory.getLogger(GameMsgEncoder.class);

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {

        if(!(msg instanceof GeneratedMessageV3)){
            super.write(ctx, msg, promise);
            return;
        }
        GeneratedMessageV3 result = (GeneratedMessageV3)msg;

        // 根据返回结果类，获取消息类型
        GameMsgProtocol.MsgCode msgCode = GameMsgRecognizer.getMsgCodeByResultClass(result.getClass());
        if(msgCode == null){
            logger.error("无法识别的消息类型, msgClass = {}", msg.getClass().getName());
            return;
        }

        byte[] body = result.toByteArray();
        ByteBuf buf = ctx.alloc().buffer(body.length + 4);
        buf.writeShort(body.length);
        buf.writeShort(msgCode.getNumber());
        buf.writeBytes(body);

        // 写出 ByteBuf
        BinaryWebSocketFrame outputFrame = new BinaryWebSocketFrame(buf);
        super.write(ctx, outputFrame, promise);
    }

}
